package com.feinno.urcs.group.interop.service;

import com.feinno.database.DataRow;
import com.feinno.database.DataTable;
import com.feinno.database.Database;
import com.feinno.urcs.group.api.FXLogicPoolService;
import com.feinno.urcs.group.api.FXUserIndexService;
import com.feinno.urcs.group.api.GroupCacheManager;
import com.feinno.urcs.group.entity.GroupIndex;
import com.feinno.urcs.group.entity.GroupMember;
import com.feinno.urcs.group.fxdb.FXPoolService;
import com.feinno.urcs.group.fxdb.PooledDatabaseLoader;
import org.helium.framework.annotations.FieldSetter;
import org.helium.framework.annotations.ServiceImplementation;
import org.helium.framework.annotations.ServiceSetter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.Map;

/**
 * @author Li.Hongbo <lihongbo@feinno.com>
 *         实际是一个GGRPDB 的DAO
 */
@ServiceImplementation
public class GroupLogicPoolServiceImpl implements FXLogicPoolService {
	private static final Logger LOGGER = LoggerFactory.getLogger(GroupLogicPoolServiceImpl.class);

	@FieldSetter("${GGRPDB}")
	private Database ggrpDb; // GGRPDB

	@Override
	public int getLogicPool(int groupId) throws Exception {
		String sql = "SELECT LogicPool FROM GGRP_SearchGroup where GroupId=?";
		GroupIndex index = null;
		DataTable dt = ggrpDb.executeTable(sql, groupId);
		if (dt.getRows().size() == 1) {
			return dt.getRow(0).getInt(1);
		}
		throw new RuntimeException("");
	}


	@FieldSetter(value = "${GRPDB_POOLS_XML}", loader = PooledDatabaseLoader.class)
	private Map<Integer, Database> dbs;

	@ServiceSetter
	private FXPoolService poolService;

	/**
	 * 获取指定PhysicalPool的GRPDB
	 *
	 * @param index 群索引
	 * @return 返回Database连接
	 * @throws SQLException
	 */
	private Database getDatabase(GroupIndex index) throws Exception {
		int logicPool = index.getLogicalPool();
		if (logicPool == 0) {
			String sql = "SELECT LogicPool FROM GGRP_SearchGroup WHERE GroupId = ?";
			DataTable dt = ggrpDb.executeTable(sql, index.getGroupId());
			logicPool = dt.getRow(0).getInt("LogicPool");
		}
		int poolid = poolService.getPhyicalPool(logicPool);
		return dbs.get(poolid);
	}

	@Override
	public int getFxGroupType(GroupIndex index) throws Exception {
		String sql = "select GroupType from GRP_Group  WHERE GroupId =?;";
		try {
			if (null == index) throw new RuntimeException("group index is null");
			DataTable dt = getDatabase(index).executeTable(sql, index.getGroupId());
			if (null != dt && dt.getRows() != null && dt.getRows().size() > 0) {
				return dt.getRow(0).getInt("GroupType");
			}
			throw new IllegalArgumentException("get GroupType fail");

		} catch (SQLException e) {
			LOGGER.error(String.format("getFxGroupType Error index=%s  ", index), e);
			throw e;
		}
	}
}
